﻿using System;
using System.Collections.Generic;
using System.Net;
using System.Text;
using System.ComponentModel;
using System.Windows.Forms;

namespace Lib.Com
{
    public class Downloader
    {
        public struct DownSender
        {
            public long BytesReceived;
            public int ProgressPercentage;
            public long TotalBytesToReceive;
            public bool DownloadCompleted;
        }

        public delegate void DownloadHandler(DownSender sender);
        public event DownloadHandler ProgressChanged;

        public string Url { get; set; }

        string destination = Application.StartupPath + @"\Updates";
        DownSender _sender = new DownSender();

        public void DownloadFile()
        {
            HttpWebRequest fileReq = (HttpWebRequest)HttpWebRequest.Create(Url);
            fileReq.GetResponse();

            Url = fileReq.Address.ToString();

            WebClient client = new WebClient();
            // Hookup DownloadFileCompleted Event
            client.DownloadFileCompleted += new System.ComponentModel.AsyncCompletedEventHandler(client_DownloadFileCompleted);
            client.DownloadProgressChanged += new DownloadProgressChangedEventHandler(client_DownloadProgressChanged);
            // Start the download and copy the file to c:\temp
            client.DownloadFileAsync(new Uri(Url), destination + @"\Fix_Pack.zip");
        }

        void client_DownloadProgressChanged(object sender, DownloadProgressChangedEventArgs e)
        {
            if (ProgressChanged != null)
            {
                _sender.BytesReceived = e.BytesReceived;
                _sender.ProgressPercentage = e.ProgressPercentage;
                _sender.TotalBytesToReceive = e.TotalBytesToReceive;

                ProgressChanged(_sender);
            }
        }

        void client_DownloadFileCompleted(object sender, System.ComponentModel.AsyncCompletedEventArgs e)
        {
            if (ProgressChanged != null)
            {
                _sender.DownloadCompleted = true;
                ProgressChanged(_sender);
            }
        }
    }
}
